<?php

class GoodsController extends BaseManageController{
	/**
	 * 
	 * @param string $id cate_id
	 */
	public function actionAdmin($id=null){
		$this->pageTitle = '商品管理列表 - ' . Yii::app()->name;
		$mod = new GoodsModel();
		$con = array(
			'site_id' => SITE_ID
		);
		if(!empty($id)){
			$con['cate'] = $id;
		}
		$total = $mod->count($con);
		$this->setPagination($total);
		$goods_list = $mod->find($con, null, $this->pager->offset, $this->pager->pageSize);
		$this->render('admin', array('list'=>$goods_list));
	}
	
	public function actionEdit($id = null, $cate = null){
		if(Yii::app()->request->isPostRequest){
			$this->_save();
		}
		$this->pageTitle = '商品编辑 - ' . Yii::app()->name;
		if($id == null){
			$goods = array(
				'_id'			=> '',
				'cate'			=> $cate,
				'stock'			=> -1,
				'price'			=> 0.00,
				'tpl_view'		=> 'view',
				'name_view'		=> '{$id}.html',
				'seo_title'		=> '{$cate_name} - {$site_name}',
				'seo_keywords'	=> '{$cate_name},{$site_keywords}',
				'seo_descript'	=> '{$site_desc}',
				'rank'			=> 255,
				'assumer'		=> 'buyer',
			);
		}else{
			$mod = new GoodsModel();
			$goods = $mod->get_by_key($id);
			if($goods['site_id'] != SITE_ID){
				throw new CHttpException(403, '非法请求！');
			}
			if(isset($goods['specs'])){
				$goods_stock_prices = Goods::model()->findAllByAttributes(array('goods_id'=>$id));
				//存在多规格，加载其价格与库存
				foreach ($goods_stock_prices as $gsp){
					$goods_spec_id = $gsp->id;
					if(isset($goods['specs'][$goods_spec_id])){
						$goods['specs'][$goods_spec_id]['stock'] = $gsp->stock;
						$goods['specs'][$goods_spec_id]['price'] = $gsp->price;
					}
				}
			}else{
				$gsp = Goods::model()->findByPk($id);
				$goods['price'] = empty($gsp)?0:$gsp->price;
				$goods['stock'] = empty($gsp)?-1:$gsp->stock;
			}
		}
		$this->render('edit', array('model'=>$goods));
	}

	/**
	 * 保存商品
	 * @param string $id 商品ID
	 */
	private function _save(){
		if(!isset($_POST['Goods'])){
			$this->ajax_error('非法请求！');
		}
		$goods = $_POST['Goods'];
		$mod = new GoodsModel();
		$goods['rank'] = intval($goods['rank']);
		if(empty($goods['_id'])){
			$goods_id = CommonHelper::gen_uuid();
			$goods_list = array();
		}else{
			$goods_id = $goods['_id'];
			//获取所有此商品规格
			$goods_list = Goods::model()->findAll(array(
				'index' 	=> 'id',
				'condition' => 'goods_id=:goods_id',
				'params'	=> array(':goods_id' => $goods_id)
			));
		}

		$transaction = Yii::app()->db->beginTransaction(); //开始事务
		try{
			if(isset($_POST['specs']) && $_POST['specs'] == 1){
				//开启了多规格
				$spec1s = $_POST['spec1'];
				$spec2s = $_POST['spec2'];
				$spec_prices = $_POST['spec_price'];
				$spec_stock = $_POST['spec_stock'];
				$has_spec2 = false;
				if(!empty($goods['spec2'])){
					//开启了规格2
					$has_spec2 = true;
				}
				$specs = array();
				foreach($spec1s as $spec_id=>$spec1_name){
					if(empty($spec1_name))continue;
					
					$spec_string_id = $spec_id;
					if(is_int($spec_string_id)){
						//新规格
						$mongo_id = new MongoId();
						$spec_string_id = $mongo_id->__toString();
						$g = new Goods();
						$g->goods_id = $goods_id;
						$g->setPrimaryKey($spec_string_id);
					}else{
						if(isset($goods_list[$spec_string_id])){
							$g = $goods_list[$spec_string_id];
						}else{
							$g = new Goods();
							$g->goods_id = $goods_id;
							$g->setPrimaryKey($spec_string_id);
						}
					}
					$specs[$spec_string_id] = array(
						'spec1' => $spec1_name,
					);
					if($has_spec2){
						$spec2_name = $spec2s[$spec_id];
						if(empty($spec2_name))continue;
						$specs[$spec_string_id]['spec2'] = $spec2_name;
					}
					$price = $spec_prices[$spec_id];
					$stock = $spec_stock[$spec_id];
					$g->attributes = array(
						'price' => $price,
						'stock' => $stock,
						'goods_id' => $goods_id,
					);
					if($g->isNewRecord){
						$g->insert();
					}else{
						unset($goods_list[$spec_string_id]);
						$g->update();
					}
				}
					
				$goods['specs'] = $specs;
			}else{
				//未开启多规格
// 				$goods['specs'] = array('$unset'=>true); //删除多规格
				
				if(isset($goods_list[$goods_id])){
					$g = $goods_list[$goods_id];
					$g->attributes = array(
						'price' => $goods['price'],
						'stock' => $goods['stock'],
					);
					$g->update();
					unset($goods_list[$goods_id]);
				}else{
					$g = new Goods();
					$g->setPrimaryKey($goods_id);
					$g->attributes = array(
						'price' => $goods['price'],
						'stock' => $goods['stock'],
						'goods_id' => $goods_id,
					);
					$g->insert();
				}
				unset($goods['spec1']);
				unset($goods['spec2']);
			}
			foreach ($goods_list as $_g){
				$_g->delete();
			}
			$transaction->commit();
		}catch(Exception $e){
			$transaction->rollback();
			$this->ajax_error($e->getMessage());
		}

		//处理图片
		$this->init_pictures('goods/' . date('Y/m/d/'), $goods);
		
		//物流快递
		if($goods['assumer'] === 'seller'){
			//卖家承担费用
			
		}
		
		//处理分类
// 		if(!empty($goods['cate'])){
// 			$goods['cate'] = GoodsCateModel::getPathIds($goods['cate']);
// 		}
		
		CommonHelper::fix(GoodsModel::$VALUE_TYPE, $goods);
		if(empty($goods['_id'])){
			//新建
			$goods['update_user_id'] = $goods['create_user_id'] = intval(Yii::app()->user->id);
			$goods['create_time'] = $goods['update_time'] = time();
			$goods['site_id'] = SITE_ID;
			$goods['_id'] = $goods_id;
			$mod->insert($goods);
		}else{
			$goods['update_time'] = time();
			$goods['update_user_id'] = intval(Yii::app()->user->id);
			$mod->update_by_key($goods['_id'], $goods);
			if(!isset($_POST['specs'])){
				$mod->delete_column_by_key($goods['_id'], 'specs,spec1,spec2');
			}
		}
		$this->ajax_info('保存成功！', $goods_id);
	}
}